package org.gavin.sharding.config;

import com.mybatisflex.core.keygen.IKeyGenerator;
import org.apache.commons.lang3.StringUtils;

/**
 * MilliGenerator
 *
 * @author grl
 * @date 2024/2/1
 */
public class MilliGeneratorConfiguration implements IKeyGenerator {

    private volatile Long lastId;

    @Override
    public Object generate(Object entity, String keyColumn) {
        return this.nextId();
    }

    private synchronized Object nextId(){
        long genId = 0L;
        while (true){
            long mills = System.currentTimeMillis();
            long nano = System.nanoTime();
            String reverse = mills+""+StringUtils.reverse(nano+"");
            genId = Long.parseLong(StringUtils.substring(reverse, 0, 19));
            if(lastId == null || genId > lastId){
                break;
            }
        }
        lastId = genId;
        return genId;
    }
}
